package com.gzhryc.shared_device.oem.micro.iot.controllers;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.cdcz.api.protocol.*;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocketSlot;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketSlotService;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.cdcz.core.models.CDCZChargeCommand;
import com.gzhryc.shared_device.cdcz.core.models.CDCZExecuteResult;
import com.gzhryc.shared_device.oem.micro.iot.MicroConstants;
import com.gzhryc.shared_device.oem.code.device.CDCZCacheManager;
import com.gzhryc.shared_device.oem.micro.iot.LocalNetworkServiceUtils;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CDCZOperateController {

    static Logger log = Logger.getLogger(CDCZOperateController.class);

    @Route(value = {"/api/v1/cdcz/charge.do"}, method = "POST")
    public CDCZHttpChargeResponse charge(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpChargeResponse apiResp = new CDCZHttpChargeResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"操作失败，请稍后再试");
        CDCZHttpChargeRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpChargeRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发充电，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZCacheManager cacheManager = new CDCZCacheManager();
                ChargeSocketSlot chargeSocketSlot = cacheManager.getChargeSocketSlot(apiReq.getBody().getDeviceSn(),apiReq.getBody().getSlotNum());
                if(chargeSocketSlot == null){
                    chargeSocketSlot = ChargeSocketSlotService.self().getJoinByKeys(apiReq.getBody().getDeviceSn(),apiReq.getBody().getSlotNum());
                    if(StringTools.isBlank(chargeSocketSlot.getCurrentTradeNo()) || !chargeSocketSlot.getCurrentTradeNo().equals(apiReq.getBody().getTradeNo())) {
                        chargeSocketSlot.setCurrentTradeNo(apiReq.getBody().getTradeNo());
                    }
                    cacheManager.saveChargeSocketSlot(chargeSocketSlot);
                }else{
                    if(StringTools.isBlank(chargeSocketSlot.getCurrentTradeNo()) || !chargeSocketSlot.getCurrentTradeNo().equals(apiReq.getBody().getTradeNo())) {
                        chargeSocketSlot.setCurrentTradeNo(apiReq.getBody().getTradeNo());
                        cacheManager.saveChargeSocketSlot(chargeSocketSlot);
                    }
                }

                CDCZChargeCommand chargeCommand = ClassTools.copy(new CDCZChargeCommand(), apiReq.getBody());
                CDCZExecuteResult executeResult = networkService.charge(chargeCommand);
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/charge/close.do"}, method = "POST")
    public CDCZHttpChargeCloseResponse closeCharge(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpChargeCloseResponse apiResp = new CDCZHttpChargeCloseResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        CDCZHttpChargeCloseRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpChargeCloseRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn()) && apiReq.getBody().getSlotNum() != null) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发关闭充电，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = networkService.closeCharge(apiReq.getBody().getDeviceSn(),apiReq.getBody().getSlotNum());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/search.do"}, method = "POST")
    public CDCZHttpSearchResponse search(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpSearchResponse apiResp = new CDCZHttpSearchResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        CDCZHttpSearchRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpSearchRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发查询主机，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = networkService.searchDevice(apiReq.getBody().getDeviceSn());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/slave_device/find.do"}, method = "POST")
    public CDCZHttpFindSlaveDeviceResponse slaveDeviceFind(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpFindSlaveDeviceResponse apiResp = new CDCZHttpFindSlaveDeviceResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"操作失败，请稍后再试");
        CDCZHttpFindSlaveDeviceRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpFindSlaveDeviceRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getMainDeviceSn()) && apiReq.getBody().getBindIndex() != null) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发查询从机，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = networkService.findSlaveDevice(apiReq.getBody().getMainDeviceSn(),apiReq.getBody().getBindIndex());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/slave_device/bind.do"}, method = "POST")
    public CDCZHttpBindSlaveDeviceResponse slaveDeviceBind(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpBindSlaveDeviceResponse apiResp = new CDCZHttpBindSlaveDeviceResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"操作失败，请稍后再试");
        CDCZHttpBindSlaveDeviceRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpBindSlaveDeviceRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getMainDeviceSn()) && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())
                && apiReq.getBody().getBindIndex() != null) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发绑定从机，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = networkService.bindSlaveDevice(apiReq.getBody().getMainDeviceSn()
                        ,apiReq.getBody().getBindIndex(),apiReq.getBody().getDeviceSn());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/slave_device/remove.do"}, method = "POST")
    public CDCZHttpRemoveSlaveDeviceResponse slaveDeviceRemove(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpRemoveSlaveDeviceResponse apiResp = new CDCZHttpRemoveSlaveDeviceResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"操作失败，请稍后再试");
        CDCZHttpRemoveSlaveDeviceRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpRemoveSlaveDeviceRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getMainDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发从机移除，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = networkService.removeSlaveDevice(apiReq.getBody().getMainDeviceSn());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/restart.do"}, method = "POST")
    public CDCZHttpRestartResponse restart(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpRestartResponse apiResp = new CDCZHttpRestartResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        CDCZHttpRestartRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpRestartRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发设备重启，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = networkService.restart(apiReq.getBody().getDeviceSn());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/mqtt_connect/change.do"}, method = "POST")
    public CDCZHttpChangeMQTTConnectResponse changeMQTTConnect(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpChangeMQTTConnectResponse apiResp = new CDCZHttpChangeMQTTConnectResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        CDCZHttpChangeMQTTConnectRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpChangeMQTTConnectRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn()) && StringTools.isNotBlank(apiReq.getBody().getType())
                && StringTools.isNotBlank(apiReq.getBody().getIp()) && StringTools.isNotBlank(apiReq.getBody().getPort())
                && StringTools.isNotBlank(apiReq.getBody().getUserName()) && StringTools.isNotBlank(apiReq.getBody().getUserPwd())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发切换MQTT连接，请求：{{1:json}}",iotId,apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = networkService.changeMQTTConnect(apiReq.getBody().getDeviceSn(),apiReq.getBody().getType(),apiReq.getBody().getIp()
                    ,apiReq.getBody().getPort(),apiReq.getBody().getUserName(),apiReq.getBody().getUserPwd());
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }

    @Route(value = {"/api/v1/cdcz/upgrade.do"}, method = "POST")
    public CDCZHttpUpgradeResponse upgrade(HttpServletRequest request, HttpServletResponse response) {
        CDCZHttpUpgradeResponse apiResp = new CDCZHttpUpgradeResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "操作失败，请稍后再试");
        CDCZHttpUpgradeRequest apiReq = WebUtils.getJsonRequest(request, CDCZHttpUpgradeRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            Long iotId = WebUtils.getAttribute(request, MicroConstants.ATTR_IOT_ID, Long.class);
            log.info("{{0}}IOT节点触发设备重启，请求：{{1:json}}", iotId, apiReq);
            ICDCZNetworkService networkService = LocalNetworkServiceUtils.getCDCZNetworkService(iotId);
            if (networkService != null) {
                CDCZExecuteResult executeResult = null;
                if (apiReq.getBody().getType() == 1) {
                    executeResult = networkService.upgrade(apiReq.getBody().getDeviceSn(),
                            apiReq.getBody().getPackagePath(), apiReq.getBody().getPackageCRC());
                } else {
                    executeResult = networkService.upgradeDownload(apiReq.getBody().getDeviceSn(),
                            apiReq.getBody().getPackagePath(), apiReq.getBody().getPackageCRC());
                }
                if (executeResult != null) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setResultCode(executeResult.getCode());
                    apiResp.getBody().setErrorMsg(executeResult.getMsg());
                    apiResp.getBody().setMessageId(executeResult.getMessageId());
                }
            } else {
                apiResp.setMsg("未找到充电插座网络服务");
            }
        }
        return apiResp;
    }
}
